package com.ovopark.organize.server.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ovopark.organize.common.base.BaseResult;
import com.ovopark.organize.server.common.constant.Constant;
import com.ovopark.organize.server.mapper.FranchiseeContractMapper;
import com.ovopark.organize.server.model.entity.DepartmentImport;
import com.ovopark.organize.server.model.entity.FranchiseeContract;
import com.ovopark.organize.server.model.entity.Users;
import com.ovopark.organize.server.model.vo.FileVo;
import com.ovopark.organize.server.service.DepartmentImportService;
import com.ovopark.organize.server.service.FranchiseeContractService;
import com.ovopark.organize.server.service.UserService;
import com.ovopark.organize.server.util.CollectionUtil;
import com.ovopark.organize.server.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class FranchiseeContractServiceImpl extends ServiceImpl<FranchiseeContractMapper, FranchiseeContract> implements FranchiseeContractService {
    Logger logger = LoggerFactory.getLogger(FranchiseeContractServiceImpl.class);
    @Resource
    private FranchiseeContractMapper baseMapper;
    @Resource
    private UserService userService;
    @Value("${myConfig.shopweb.websocket-url}")
    private String shopwebWebsocketUrl;

    @Resource
    private DepartmentImportService departmentImportService;

    @Override
    public void saveContractByUserId(Integer userId, Integer groupId, List<FileVo> contractUrl) {
       // List<FranchiseeContract> oldContract = getContractByUserId( userId,  groupId);
      //  Map<String,FileVo> urlAndFileName = contractUrl.stream().collect(Collectors.toMap(FileVo::getUrl,Function.identity()));

      /*  if(CollectionUtil.isNotEmpty(oldContract)){
            List<Integer> deletedUrlId = new ArrayList<>();
            for (FranchiseeContract old:oldContract ) {
                String url = old.getContractUrl();
                FileVo contract = urlAndFileName.get(url);
                if(contract == null){
                    // 需要删除
                    deletedUrlId.add(old.getId());
                }else if(!contract.getFileName().equals(old.getFileName())){
                   // 更新
                    old.setFileName(contract.getFileName());
                    saveContractBean(old);
                }else {
                    // 名称相同 不做处理
                    contractUrl.remove(contract);
                }

            }
            if(CollectionUtil.isNotEmpty(deletedUrlId)){
                deleteFranchiseeList( userId,  groupId, deletedUrlId);
            }
        }*/

        deleteFranchiseeList( userId,  groupId, new ArrayList<>());
        if(CollectionUtil.isNotEmpty(contractUrl)){
            for (FileVo url:contractUrl  ) {
                FranchiseeContract contract = new FranchiseeContract();
                contract.setContractUrl(url.getUrl());
                contract.setGroupId(groupId);
                contract.setUserId(userId);
                contract.setFileName(url.getFileName());
                saveContractBean(contract);
            }

        }


    }

    @Override
    public List<FranchiseeContract> getContractByUserId(Integer userId, Integer groupId) {
        LambdaQueryWrapper<FranchiseeContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FranchiseeContract::getUserId,userId);
        queryWrapper.eq(FranchiseeContract::getGroupId,groupId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public FranchiseeContract saveContractBean(FranchiseeContract contract) {
        if(contract.getId() !=null){
            baseMapper.updateById(contract);
        }else {
            baseMapper.insert(contract);
        }
        return contract;
    }

    @Override
    public Map<Integer, List<FranchiseeContract>> getFranchiseeListByUsers(Integer enterpriseId, List<Integer> userIds) {
        Map<Integer, List<FranchiseeContract>> franchiseeContractMap = new HashMap<>();
        if(enterpriseId !=null || CollectionUtil.isNotEmpty(userIds)){
            List<FranchiseeContract> list =  getFranchiseeList( enterpriseId,  userIds);
            if(CollectionUtil.isNotEmpty(list)){
                franchiseeContractMap = list.stream().collect(Collectors.groupingBy(FranchiseeContract::getUserId));
            }
        }

        return franchiseeContractMap;
    }

    @Override
    public List<FranchiseeContract> getFranchiseeList(Integer enterpriseId, List<Integer> userIds) {
        LambdaQueryWrapper<FranchiseeContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FranchiseeContract::getGroupId,enterpriseId);
        if(CollectionUtil.isNotEmpty(userIds)){
            queryWrapper.in(FranchiseeContract::getUserId,userIds);
        }
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteFranchiseeList(Integer userId, Integer groupId, List<Integer> id) {
        LambdaQueryWrapper<FranchiseeContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FranchiseeContract::getUserId,userId);
        queryWrapper.eq(FranchiseeContract::getGroupId,groupId);
        if(CollectionUtil.isNotEmpty(id)){
            queryWrapper.in(FranchiseeContract::getId,id);
        }
         baseMapper.delete(queryWrapper);


    }

    @Override
    public BaseResult importFranchiseeContract(File multipartFile, Integer curUserId, Integer groupId, String remoteIp, String platform, Locale finalLocale) {

        Users users = userService.getUsersById(curUserId);
        // 加盟商名称---List<Url>
        Map<String, List<FranchiseeContract>> result = new HashMap<>();
        Integer franchiseeType = 1;
        List<Users> usersList = userService.findUsersByFranchiseeType(groupId,franchiseeType);
        List<String> fieldNames = new ArrayList<>();
        List<DepartmentImport> departmentImports = new ArrayList<>();
        List<String> successList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(usersList)) {
            Map<String, Users> usersMap = usersList.stream().collect(Collectors.toMap(Users::getUserName, Function.identity()));
            result = FileUtil.unZip(multipartFile,groupId,curUserId);
            // 根据 文件名称 上传 后 保存
            if(CollectionUtil.isNotEmpty(result)){
                List<FranchiseeContract> errorList = result.get("error");
                if(CollectionUtil.isNotEmpty(errorList)){
                   fieldNames = errorList.stream().map(FranchiseeContract::getFileName).collect(Collectors.toList());
                   String errorNames = "franchiseeContract-importLogFormatError:"+ String.join(",",fieldNames);
                   List<String> contentList = new ArrayList<>();
                    contentList.add(errorNames);
                    DepartmentImport departmentImport = new DepartmentImport();
                    departmentImport.setGroupId(groupId);
                    departmentImport.setCreateId(curUserId);
                    departmentImport.setCreateTime(new Date());
                    departmentImport.setContentList(contentList);
                    departmentImport.setAddDate(false);
                    departmentImports.add(departmentImport);
                    result.remove("error");
                }
                if(CollectionUtil.isNotEmpty(result)){
                    List<String> contentList = new ArrayList<>();

                    for (Map.Entry<String, List<FranchiseeContract>> entry:result.entrySet()) {
                        String franchiseeName = entry.getKey();
                        Users franchUser  =  usersMap.get(franchiseeName);
                        if(franchUser !=null){
                            List<FranchiseeContract> list = entry.getValue();
                            if(CollectionUtil.isNotEmpty(list)){
                                for (FranchiseeContract contract:list) {
                                    contract.setUserId(franchUser.getId());
                                    contract.setGroupId(groupId);
                                    baseMapper.insert(contract);
                                    String fileName = franchiseeName+"-"+contract.getFileName();
                                    successList.add("franchiseeContract:"+fileName);
                                }
                            }
                        }else {
                            fieldNames.add(franchiseeName);
                            contentList.add("exportUser.franchiseeType.1-importLogNotMatchedTo:"+franchiseeName);
                            DepartmentImport departmentImport = new DepartmentImport();
                            departmentImport.setGroupId(groupId);
                            departmentImport.setCreateId(curUserId);
                            departmentImport.setCreateTime(new Date());
                            departmentImport.setContentList(contentList);
                            departmentImport.setAddDate(false);
                            departmentImports.add(departmentImport);
                        }

                    }


                    if(CollectionUtil.isNotEmpty(successList)){
                        DepartmentImport departmentImport = new DepartmentImport();
                        departmentImport.setGroupId(groupId);
                        departmentImport.setCreateId(curUserId);
                        departmentImport.setCreateTime(new Date());
                        departmentImport.setSuccessContentList(successList);
                        departmentImport.setAddDate(false);
                        departmentImports.add(departmentImport);
                    }



                }

            }

        }

      //  Integer total = result.size();
      //  Integer finalSuccess = total - fieldNames.size();
        String messageData =  "导入加盟商合同成功,成功数："+successList.size()+"失败数："+fieldNames.size();
        Map<String, String> map = new HashMap<>();
        map.put("userId", curUserId+"");
        map.put("clients", Constant.CLIENT_WEB);
        map.put("message", messageData);
        map.put("messageType", "3009");

        ///Users user, List<Integer> operationIds, String remoteIp, String platform, List<DepartmentImport> departmentImports, String operation,
        //                          String desciption, String nkey, String message, String  messageType,Boolean isLog

        logger.info("importFranchiseeContract:"+JSONObject.toJSONString(map) );
        departmentImportService.saveLogAndImport(users, null, remoteIp, platform, departmentImports, "importFranchiseeContract", "导入加盟商合同"+JSONObject.toJSONString(result), "importLogFranchiseeContract", messageData, "3009", false);
        return BaseResult.success();
    }


}
